<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>HyperCMF</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 注意：项目正式环境请勿引用该地址 -->
    <link rel="stylesheet" href="/static/layui/css/layui.css" media="all">
    <script src="/static/js/jquery.min.js?v=2.1.4"></script>
    <script src="/static/js/base.js"></script>
    <script src="/static/layui/layui.2.7.6.js"></script>
</head>
<body>
<div class="layui-fluid" style="margin-top: 10px">
    <div class="layui-card">
        <div class="layui-card-body">
            <table class="layui-hide" id="dataTable" lay-filter="dataTable"></table>
        </div>
    </div>
</div>
<script type="text/html" id="toolbar">
    <div class="layui-btn-container">

        <button class="layui-btn layui-btn-sm" lay-event="add">添加角色</button>
    </div>
</script>

<script type="text/html" id="cityTpl">
    <select id="City1" class="layui-border" lay-ignore>
        <option value="0">禁用</option>
        <option value="1">正常</option>
    </select>
</script>

<script type="text/html" id="bar">
    <a class="layui-btn layui-btn-xs" lay-event="privilege">权限管理</a>
    {{#  if(d.status ==1){ }}
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="ban">禁用</a>
    {{#  }else if(d.status ==0){ }}
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="open">启用</a>
    {{#  } }}
</script>

<script>
    layui.use(['table', 'dropdown','layer','laydate'], function(){
        var table = layui.table;
        var dropdown = layui.dropdown;
        var layer = layui.layer;
        var laydate = layui.laydate;

        // layer.msg('本示例演示的数据为静态模拟数据，<br>实际使用时换成您的真实接口即可。', {
        //     closeBtn: 1,
        //     icon: 6,
        //     time: 21*1000,
        //     offset: '21px'
        // });
        $.ajax({
            url:'/admin/node/allNode',
            data:{},
            async:false,
            type:'get',
            dataType:'json',
            headers:{
                'token':localStorage.getItem('hypercmfname')+'_'+localStorage.getItem('token'),
                'accept':'*/*'
            },
            success:function(res){
                let nodes = res.data
                if(res.code==1){
                    // 创建渲染实例
                    table.render({
                        elem: '#dataTable'
                        ,url:'/admin/user/role' // 此处为静态模拟数据，实际使用时需换成真实接口
                        ,headers:{token:localStorage.getItem('hypercmfname')+'_'+localStorage.getItem('token')}
                        ,toolbar: '#toolbar'
                        ,defaultToolbar: ['filter', 'exports', 'print', {
                            title: '帮助'
                            ,layEvent: 'LAYTABLE_TIPS'
                            ,icon: 'layui-icon-tips'
                        }]
                        ,height: 'full-200' // 最大高度减去其他容器已占有的高度差
                        ,cellMinWidth: 80
                        // ,totalRow: true // 开启合计行
                        ,page: true
                        ,response: {
                            statusCode: 1 //重新规定成功的状态码为 200，table 组件默认为 0
                        }
                        ,parseData: function(res){ //将原始数据解析成 table 组件所规定的数据
                            console.log(res.data.data)
                            return {
                                "code": res.code, //解析接口状态
                                "msg": res.msg, //解析提示文本
                                "count": res.data.total, //解析数据长度
                                "data": res.data.data //解析数据列表
                            };
                        }
                        ,cols: [[
                            {type: 'checkbox', fixed: 'left'}
                            ,{field:'id', fixed: 'left', width:80, title: 'ID', sort: true}
                            ,{field:'role_name', width:120, title: '角色名称'}
                            ,{field:'rule', title:'权限',templet: function(d){
                                    let newArr = []
                                    if(d.rule=='*') return '全部'
                                    const result = d.rule.split(',').map(id=>nodes.find(item=>item.id==id)?.title||'').join('，')
                                    return result
                                }
                            }
                            ,{fixed: 'right', title:'操作', width: 200,minWidth: 125, toolbar: '#bar'}
                        ]]
                        ,done: function(){
                            var id = this.id;

                        }
                        ,error: function(res, msg){
                            console.log(res, msg)
                        }
                    });
                }else{
                    layer.alert(res.msg,{icon:5})//1√，2×，3问号，4锁，5不开心，6开心
                }
            },error:function(res){
                layer.alert('请求失败',{icon:2})
            }
        })

        // 工具栏事件
        table.on('toolbar(dataTable)', function(obj){
            var id = obj.config.id;
            var checkStatus = table.checkStatus(id);
            var othis = lay(this);
            switch(obj.event){
                case 'getCheckData':
                    var data = checkStatus.data;
                    layer.alert(layui.util.escape(JSON.stringify(data)));
                    break;
                case 'add':
                    layer.open({
                        title: '修改基本信息',
                        type: 2,
                        shadeClose:true,
                        area: ['80%','80%'],
                        content: '/admin/user/add_role.html'
                    })
            };
        });

        //触发单元格工具事件
        table.on('tool(dataTable)', function(obj){ // 双击 toolDouble
            var data = obj.data;
            console.log(obj)
            if(obj.event === 'edit'){
                layer.open({
                    title: '修改基本信息',
                    type: 2,
                    shadeClose:true,
                    area: ['80%','80%'],
                    content: '/admin/user/edit_role.html?role_name='+obj.data.role_name+'&id='+obj.data.id
                });
            }else if(obj.event === 'ban'){
                var a = Math.ceil(Math.random()*100)
                layer.prompt({title: '为了防止误操作，请输入：'+ a, formType: 2}, function(text, index){
                    if(text!=a){
                        layer.msg('验证失败');
                        setTimeout(function () {
                            layer.close(index);
                        },1000)
                    }else{
                        $.ajax({
                            url:'/admin/user/banRole',
                            data:{id:obj.data.id,status:0},
                            async:false,
                            type:'post',
                            dataType:'json',
                            headers:{
                                'token':localStorage.getItem('hypercmfname')+'_'+localStorage.getItem('token'),
                                'accept':'*/*'
                            },
                            success:function(res){
                                if(res.code==1){
                                    layer.msg('操作成功',{
                                        icon: 1,
                                        time: 1000 //1秒关闭（如果不配置，默认是3秒）
                                    },function () {
                                        layer.closeAll()
                                        table.reload('dataTable')
                                    })

                                }else{
                                    layer.alert(res.msg,{icon:5})//1√，2×，3问号，4锁，5不开心，6开心
                                }
                            },error:function(res){
                                layer.alert('请求失败',{icon:2})
                            }
                        })
                    }
                });

            }else if(obj.event === 'open'){
                var a = Math.ceil(Math.random()*100)
                layer.prompt({title: '为了防止误操作，请输入：'+ a, formType: 2}, function(text, index){
                    if(text!=a){
                        layer.msg('验证失败');
                        setTimeout(function () {
                            layer.close(index);
                        },1000)
                    }else{
                        $.ajax({
                            url:'/admin/user/banRole',
                            data:{id:obj.data.id,status:1},
                            async:false,
                            type:'post',
                            dataType:'json',
                            headers:{
                                'token':localStorage.getItem('hypercmfname')+'_'+localStorage.getItem('token'),
                                'accept':'*/*'
                            },
                            success:function(res){
                                if(res.code==1){
                                    layer.msg('操作成功',{
                                        icon: 1,
                                        time: 1000 //1秒关闭（如果不配置，默认是3秒）
                                    },function () {
                                        layer.closeAll()
                                        table.reload('dataTable')
                                    })

                                }else{
                                    layer.alert(res.msg,{icon:5})//1√，2×，3问号，4锁，5不开心，6开心
                                }
                            },error:function(res){
                                layer.alert('请求失败',{icon:2})
                            }
                        })
                    }
                });

            }else if(obj.event == 'privilege'){
                layer.open({
                    title: '修改权限',
                    type: 2,
                    shadeClose:true,
                    area: ['90%','90%'],
                    content: '/admin/user/power.html?a=3&id='+obj.data.id
                });
            }
        });


    });

</script>

</body>
</html>